package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param category

     * @return
     */
    @PostMapping
    public R saveCategory(@RequestBody Category category) {
        boolean save = categoryService.save(category);
        if (save) {
            return R.success(category);
        } else {
            return R.error("分类添加失败");
        }
    }

    /**
     * 分类分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R selectByPageAndCondition(Integer page, Integer pageSize) {
        IPage<Category> pageinfo = new Page<>(page, pageSize);
        categoryService.page(pageinfo);
        return R.success(pageinfo);
    }

    /**
     * 删除分类
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete(Long id) {

        categoryService.remove(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R updateCategory(@RequestBody Category category, HttpSession session) {
//        category.setUpdateTime(LocalDateTime.now());
//        Long empId = (Long) session.getAttribute("employee");
//        category.setUpdateUser(empId);
        boolean b = categoryService.updateById(category);
        if (b) {
            return R.success(null);
        } else {
            return R.error("修改失败");
        }
    }


    @GetMapping("/list")
    public R list(Integer type) {
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(type!=null,Category::getType, type).orderByDesc(Category::getSort);
        List<Category> list = categoryService.list(qw);
        if (list.size() > 0) {
            return R.success(list);
        }else{
            return R.error("暂无该菜品分类");
        }

    }
    /**
     * 根据条件查询分类
     * @param category
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Category>> list(Category category){
//        //条件构造器
//        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
//        //添加条件
//        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
//        //添加排序条件
//        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
//        List<Category> list = categoryService.list(queryWrapper);
//        return R.success(list);
//    }


}
